/*
 * Copyright (C) 2012 DataSymphony (http://datasymphony.com.au)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package au.com.ds.restty.js.co;

import java.util.LinkedList;
import java.util.List;

import au.com.ds.restty.exc.InvalidTemplate;
import au.com.ds.restty.google.GoogleTokenProvider;
import au.com.ds.restty.js.JsAnyObject;
import au.com.ds.restty.js.JsArray;
import au.com.ds.restty.js.JsBoolean;
import au.com.ds.restty.js.JsObject;
import au.com.ds.restty.js.JsObjectFactory;
import au.com.ds.restty.js.JsString;

public class GoogleAuthenticator extends ContextObject {
	private static final long serialVersionUID = -1836811882132750051L;
	private GoogleTokenProvider mTokenManager = new GoogleTokenProvider();
	private boolean mUseCache = true;

	@Override
	public Object getDefaultValue(Class<?> hint) {
		return toString();
	}

	public String jsFunction_getToken(Object scopes, String tag) throws Exception {
		// tag is used to persist corresponding tokens - to support multiple Google accounts, identify scopes
		List<String> scopeList = new LinkedList<String>();
		JsAnyObject scopeObj = JsObjectFactory.create(scopes);
		JsString scopeString = scopeObj.as(JsString.class);
		if (scopeString != null) {
			scopeList.add(scopeString.getValue());
		} else {
			JsArray scopeArr = scopeObj.as(JsArray.class);
			if (scopeArr == null) {
				throw new InvalidTemplate("[Scope] must be defined as a string or an array of strings");
			}
			
			for (JsAnyObject scopeItem : scopeArr.getValue()) {
				JsString scopeItemStr = scopeItem.as(JsString.class);
				if (scopeItemStr == null) {
					throw new InvalidTemplate("[Scope] must be defined as a string or an array of strings");
				}
				
				scopeList.add(scopeItemStr.getValue());
			}
		}
		
		return mTokenManager.getToken(scopeList, tag, mUseCache);
	}

	@Override
	public void setUp(JsObject settings) {
		JsBoolean useCache = settings.get("useCache").as(JsBoolean.class);
		if (useCache != null) {
			mUseCache = useCache.getValue();
		} else {
			throw new InvalidTemplate("[useCache] parameter is not defined for GoogleAuthenticator");
		}
	}
}
